package com.bluefox.uac.utils;

import cn.hutool.json.JSONObject;
import com.bluefox.uac.exception.BadRequestException;
import com.bluefox.uac.security.CustomAuthenticationToken;
import com.bluefox.uac.security.LoginUserBean;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * 获取当前登录的用户
 *
 * @author Zheng Jie
 * @date 2019-01-17
 */
public class SecurityUtils {

    public static LoginUserBean getUserDetails() {
        LoginUserBean loginUserBean = null;
        try {
            Authentication authentication =
                    SecurityContextHolder.getContext().getAuthentication();
            if (authentication instanceof CustomAuthenticationToken) {
                CustomAuthenticationToken token = (CustomAuthenticationToken) authentication;
           return token.getDetails();
            }
        } catch (Exception e) {
            throw new BadRequestException(HttpStatus.UNAUTHORIZED, "登录状态过期");
        }
        return null;
    }

    /**
     * 获取系统用户名称
     *
     * @return 系统用户名称
     */
    public static String getUsername() {
        Object obj = getUserDetails();
        return new JSONObject(obj).get("username", String.class);
    }

    /**
     * 获取系统用户id
     *
     * @return 系统用户id
     */
    public static Long getUserId() {
        Object obj = getUserDetails();
        return new JSONObject(obj).get("id", Long.class);
    }
}
